package  
{
	import flash.display.Sprite;
	import flash.filters.BlurFilter;
	import flash.geom.Vector3D;
	
	public class Boid extends Sprite
	{
		private const DEPTH:Number 	= 400;
		public var mFriend:Boid 	= null;
		public var mEnemy:Boid 		= null;
		private var mSpeed:Number 	= 10;
		private var mBind:Vector3D 	= new Vector3D();
		private var mVec:Vector3D 	= new Vector3D();
		public var mPos:Vector3D 	= new Vector3D();
		
		/**
		 * ...
		 * @author Guillaume Sylvain
		 */
		public function Boid() 
		{
			this.graphics.beginFill(0xF6F87B);
			this.graphics.drawCircle(0, 0, 2);
			this.graphics.endFill();
			this.filters = [new BlurFilter()];
			mSpeed += Math.random() - 0.5;
		}
		
		public function Update():void
		{
			Move(mFriend.mPos, 2 * mSpeed);
			Move(mEnemy.mPos, -1 * mSpeed);
			MoveToBind(mBind, 0.5 * mSpeed);
			Refresh();
		}
		
		private function Refresh():void
		{
			x = mPos.x;
			y = mPos.y;
			
			var percent:Number = (DEPTH - mPos.z) / DEPTH;
			percent < 0 ? 0 : percent;
			percent > 100 ? 100 : percent;
			
			scaleX = scaleY = percent * (4 - 1) + 1; // 4 = Front objects will be 4x larger than rear objects.
			alpha = (1 - percent) * (1 - 0.2) + 0.2;
		}
		
		private function MoveToBind(aTarget:Vector3D, aRatio:Number):void
		{
			mVec.x = aTarget.x - mPos.x;
			mVec.y = aTarget.y - mPos.y;
			mVec.z = aTarget.z - mPos.z
			
			aRatio *= (mVec.length / 200);
			
			mVec.normalize();
			mVec.scaleBy(aRatio);
			
			mPos.x += mVec.x;
			mPos.y += mVec.y;
			mPos.z += mVec.z;
		}
		
		private function Move(aTarget:Vector3D, aRatio:Number):void 
		{
			mVec.x = aTarget.x - mPos.x;
			mVec.y = aTarget.y - mPos.y;
			mVec.z = aTarget.z - mPos.z;
			
			if (mVec.length < 20)
			{
				aRatio *= (mVec.length / 20) / 2;
			}
			
			mVec.normalize();
			mVec.scaleBy(aRatio);
			
			mPos.x += mVec.x;
			mPos.y += mVec.y;
			mPos.z += mVec.z;
		}
		
		public function SetBindPos(aX:Number, aY:Number, aZ:Number = 0):void
		{
			mBind.x = aX;
			mBind.y = aY;
			mBind.z = aZ;
		}
	}
}